package service

import (
	"api_interface/dao"
	"api_interface/entity"

	"github.com/jinzhu/gorm"
)

// 评论（测试完成）
func CreateComment(comment *entity.CommentInfo) (err error) {
	tx := dao.SqlSession.Begin()
	if err = tx.Create(comment).Error; err != nil {
		tx.Rollback()
		return err
	}
	if err = tx.Model(&entity.QuestionInfo{}).Where("id=?", comment.Qid).Update("comments", gorm.Expr("comments + 1")).Error; err != nil {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}

//点赞提问or取消点赞（测试完成）

func LikeCommentOrDeleteLike(aid int, cid int) (err error) {
	var likedInfo entity.LikedInfo
	tx := dao.SqlSession.Begin()
	// 先查找是否存在点赞记录
	if err := tx.Where("aid =? AND cid =?", aid, cid).First(&likedInfo).Error; err == nil {
		// 记录存在，执行取消点赞操作（CommentInfo的Lik减一，并删除LikedInfo记录）
		if err := tx.Model(&entity.CommentInfo{}).Where("id =?", cid).Update("lik", gorm.Expr("lik -?", 1)).Error; err != nil {
			tx.Rollback()
			return err
		}
		if err := tx.Where("aid =? AND cid =?", aid, cid).Delete(&entity.LikedInfo{}).Error; err != nil {
			tx.Rollback()
			return err
		}
	} else if gorm.ErrRecordNotFound == err {
		// 记录不存在，执行点赞操作（CommentInfo的Lik加一，并创建新的LikedInfo记录）
		if err := tx.Model(&entity.CommentInfo{}).Where("id =?", cid).Update("lik", gorm.Expr("lik +?", 1)).Error; err != nil {
			tx.Rollback()
			return err
		}
		newLikedInfo := entity.LikedInfo{
			Cid: cid,
			Aid: aid,
			Qid: 1,
		}
		if err := tx.Create(&newLikedInfo).Error; err != nil {
			tx.Rollback()
			return err
		}
	} else {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}

//获取评论（测试完成）

func GetComments(aid int, qid int) (commentsWithLiked *[]entity.CommentInfoWithLiked, err error) {
	var commentlist []entity.CommentInfo
	if err = dao.SqlSession.Where("qid=?", qid).Find(&commentlist).Error; err != nil {
		return nil, err
	}
	var commentsWithLikedlist []entity.CommentInfoWithLiked
	for i, data := range commentlist {
		var l bool
		var likes []entity.LikedInfo
		dao.SqlSession.Where("aid = ? AND cid = ?", aid, data.Id).Find(&likes)
		if len(likes) == 0 {
			l = false
		} else {
			l = true
		}
		commentsWithLikedlist = append(commentsWithLikedlist, entity.CommentInfoWithLiked{
			Comments: commentlist[i],
			Liked:    l,
		})
	}
	commentsWithLiked = &commentsWithLikedlist
	return
}
